//https://www.cnblogs.com/fsg6/p/13204365.html?utm_source=tuicool
//https://blog.csdn.net/u014225733/article/details/98722635
// AxiosRequestConfig, ResponseType, AxiosInstance 最外层交互API
import axios, { AxiosRequestConfig, ResponseType, AxiosInstance } from 'axios'
import { SERVER } from 'constants/server'
import { message } from 'antd';
const TIMEOUT =40000
//声明文件
//https://blog.csdn.net/niitlcj/article/details/80808445

const MIME_TYPE : IDictionary<ResponseType>= {
  JSON: 'json',
}

//https://blog.csdn.net/niitlcj/article/details/80808445
const createInstance = () => {
  const instance = axios.create({
    baseURL: SERVER,
    withCredentials: true,//`withCredentials` 表示跨域请求时是否需要使用凭证
    timeout: TIMEOUT,
    //不声明导致爆红
    responseType: MIME_TYPE.JSON,//` 表示服务器响应的数据类型，可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  })
  //局部拦截器
  instance.interceptors.response.use(handleResponse, handleError)

  return instance
}


const handleResponse = (response: any) => {
  return response.data
}

const handleError = (error: any) => {
  const { response, message } = error
  return Promise.reject(response ? new Error(response.data.message || message) : error)
}



const toastError = (error: any) => {
  const { response ,message } = error
  message.success({
    content:response?.data?.message || message ,
  });
  return Promise.reject(error)
}

interface Instance extends AxiosInstance {
  (config: AxiosRequestConfig): Promise<any>
}
export const requestWithoutErrorToast: Instance = createInstance()

const request: Instance = createInstance()
//全局拦截器
request.interceptors.response.use(undefined, toastError)

export default request

